package cn.wgx.module.file.service.imp;

import cn.wgx.common.util.UUIDUtils;
import cn.wgx.module.file.entity.FileInfo;
import cn.wgx.module.file.entity.FileType;
import cn.wgx.module.file.service.FileService;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.Serializable;

/**
 * @author 作者 owen
 * @version 创建时间：2017年11月12日 上午22:57:51
 * 七牛云oss存储文件
 */
@Slf4j
@Service("qiniuOssServiceImpl")
public class QiniuOssServiceImpl extends FileService {


    @Autowired
    private UploadManager uploadManager;

    @Autowired
    private BucketManager bucketManager;

    @Autowired
    private Auth auth;

    @Value("${qiniu.oss.bucketName:xxxxx}")
    private String bucket;

    @Value("${qiniu.oss.endpoint:xxxxx}")
    private String endpoint;

    public void doUploadFile(MultipartFile file, FileInfo fileInfo) {
        String fileName = file.getOriginalFilename();
        String fileId = fileInfo.getFile_id() == null? UUIDUtils.getGUID32():fileInfo.getFile_id();
        StringBuffer tempFilePath = new StringBuffer();
        tempFilePath.append(fileId);
        // 检查文件后缀格式
        if(fileName.contains(".")){
            String ext = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            tempFilePath.append(".").append(ext);
        }
        try {
            // 调用put方法上传
            Response response = uploadManager.put(file.getBytes(), tempFilePath.toString(), auth.uploadToken(bucket));
//            //解析上传成功的结果
//            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
//            System.out.println(putRet.key);
//            System.out.println(putRet.hash);
//            // 打印返回的信息
        } catch (Exception e) {

        }
        String url = endpoint + "/" + tempFilePath;
        fileInfo.setUrl(url);
        fileInfo.setDisPath(url);


    }

    public boolean doDelete(Serializable id) {
        FileInfo fileInfo = getById(id);
        try {
            Response response = bucketManager.delete(this.bucket, fileInfo.getDisPath());
            int retry = 0;
            while (response.needRetry() && retry++ < 3) {
                response = bucketManager.delete(bucket, fileInfo.getDisPath());
            }
        } catch (QiniuException e) {
            return false;
        }
        return true;

    }

    @Override
    public FileType getFileType() {
        return FileType.QINIU;
    }
}
